/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package gride.plugin.templates;

import gride.GrideSettings;
import gride.events.EventListener;
import gride.events.GrideEvents;
import gride.plugin.GridePlugin;
import gride.project.GrideScript;
import gride.groovy.Regex;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import javax.swing.JMenuItem;

/**
 *
 * @author lukasz
 */
public class TemplatesPlugin extends GridePlugin
{
    /**
     *
     */
    public static String SCRIPT_TEMPLATE_FILE = "script_template";


    // <editor-fold defaultstate="expanded" desc="Private Members">

    private JMenuItem editTemplateMenuItem;

    // </editor-fold>


    // <editor-fold defaultstate="expanded" desc="Constructors">

    /**
     * 
     */
    public TemplatesPlugin()
    {
        editTemplateMenuItem = new JMenuItem("Edit Script Template");

        editTemplateMenuItem.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                editTemplateAction();
            }
        });
    }

    // </editor-fold>


    // <editor-fold defaultstate="expanded" desc="Getters/Setters">

    // </editor-fold>


    // <editor-fold defaultstate="expanded" desc="Public Methods">

    /**
     *
     */
    public void editTemplateAction()
    {
        // have to wrap the template file up in a GrideScript
        // for the source editor to open it
        GrideScript script = new GrideScript(SCRIPT_TEMPLATE_FILE + ".tmp", "");
        script.setControlledPackage(false);

        try
        {
            script.setSourceFile(
                            new File(GrideSettings.SETTINGS_DIR + "/" +
                                     SCRIPT_TEMPLATE_FILE));
        } catch (IOException ex)
        {
            return;
        }

        Object[] args = { script };
        eventManager.raiseEvent(GrideEvents.OPEN_FILE, args);
    }

    /**
     *
     */
    @Override
    public void activate() 
    {
        final TemplatesPlugin myself = this;

        // add the menuitem to the Tools menu
        guiManager.addMenuItem(editTemplateMenuItem, "Tools");

        // listen to PROJECT_NEW_SCRIPT events
        // each time a new script is created, we will write
        // the contents of our template to it
        eventManager.addListener(GrideEvents.PROJECT_NEW_SCRIPT,
                                 new EventListener()
        {
            public Object whoIsListening()
            {
                return myself;
            }

            public void eventRaised(String eventID, Object[] args)
            {
                GrideScript script = (GrideScript) args[0];

                try
                {
                    // read the template
                    String template = readFileContents(
                         new File(GrideSettings.SETTINGS_DIR + "/" +
                                  SCRIPT_TEMPLATE_FILE));

                    // substitute known macros, remove others
                    for (String macro : Regex.getTemplateMacros(template))
                        if (macro.equals("${User}"))
                            template = template.replace(macro,
                                           System.getProperty("user.name"));

                        else if (macro.equals("${ScriptName}"))
                            template = template.replace(macro,
                                                      script.getFullName());

                        else if (macro.equals("${PackageDeclaration}"))
                        {
                            if (script.getPackage().equals(""))
                                template = template.replace(macro, "");
                            else
                                template = template.replace(macro,
                                       "package " + script.getPackage() + "\n");
                        }
                        else
                            template = template.replace(macro, "");


                    // write the template to the source file of the newly
                    // added script
                    FileWriter writer = new FileWriter(
                                  script.getSourcefile().getAbsolutePath());
                    writer.write(template);
                    writer.close();
                }
                catch (IOException e)
                {
                    // io exception - don't write template to file
                }
            }
            
        });

        active = true;
    }

    /**
     *
     */
    @Override
    public void deactivate()
    {
        guiManager.removeMenuItem(editTemplateMenuItem);
        eventManager.removeAllListenersFrom(this);

        active = false;
    }

    // </editor-fold>


    // <editor-fold defaultstate="expanded" desc="Private Methods">

    /**
     * Returns a String containing the contents of the given file
     * @param file
     * @return
     * @throws java.io.IOException
     */
    private String readFileContents(File file) throws IOException
    {
        StringBuilder fileContents = new StringBuilder();
        char[] buf = new char[1024];

        FileReader reader = new FileReader(file);

        int charsRead = 0;
        while ((charsRead = reader.read(buf)) != -1) {
            fileContents.append(buf, 0, charsRead);
        }

       return fileContents.toString();
    }

    // </editor-fold>

}
